const Service = require('egg').Service;

class HomeService extends Service {
    async getBlog() {
        const { ctx, app } = this;
        // 分页 排序 id查询
        // CRUD语句中Select 不支持模糊查询
        // 如果要模糊查询 最好先用原生sql
        const { id, sortBy, sortType, pageIndex, pageSize } = ctx.query; // ?id=1  params /1  body {}
        const option = {}
        if (id) {
            option.where = { id }
        }
        if (sortBy && sortType) {
            option.orders = [[sortBy, sortType]]
        }
        if (pageSize && pageIndex) {
            option.limit = pageSize // 返回数据量
            option.offset = (pageIndex - 1) * pageSize // 数据偏移量
        }
        const res = await app.mysql.select('blogs', option)
        let totalSql = `select count(id) as total from blogs where 1=1 `
        if (id) { // 影响数量的筛选 总数也需要改变
            totalSql += `and id=${id}`
        }
        const [{ total }] = await app.mysql.query(totalSql)
        return {
            list: res,
            total: total
        }
    }
    async addBlog() {
        // 添加
        const { ctx, app } = this;
        const { title, content, author } = ctx.request.body;
        const res = await app.mysql.insert('blogs', { title, content, author, create_time: Date.now() })
        return res
    }
    async editBlog() {
        // 编辑
        const { ctx, app } = this;
        const { title, content, id } = ctx.request.body;
        const res = await app.mysql.update('blogs', { title, content, id })
        return res
    }
    async delBlog() {
        // 删除
        const { ctx, app } = this;
        const { id } = ctx.params;
        const res = await app.mysql.delete('blogs', { id })
        return res
    }
}

module.exports = HomeService;
